
const { md5, createToken } = require('../util/common');
const { user: UserModal } = require('../db');

// 注册
const registerRoute = async ctx => {
    const { mobile, password, username } = ctx.request.body;
    // 连接数据库
    const isAlreadyData = await UserModal.find({ mobile });
    // 用户已存在
    if (isAlreadyData) {
        ctx.body = { message: '用户已存在', result: false };
        return;
    };
    // 通过base64和md5加密
    const encryptionPass = md5(password);
    // 往数据库中添加
    try {
        await UserModal.createData({
            mobile,
            password: encryptionPass,
            username
        });
        const data = await UserModal.find({ mobile });
        const token = createToken(data.id);
        ctx.body = { message: '', result: { token } };
    } catch (error) {
        throw error
    }
};

// 登录
const loginRoute = async ctx => {
    const { mobile, password } = ctx.request.body;
    // 获取接口过来的密码
    const encryptionPass = md5(password);
    const result = await UserModal.find({ mobile });
    if (!result) {
        ctx.body = { message: '用户不存在，请注册', result: false };
        return;
    }
    const token = createToken(result.id);
    // 连接数据库获取密码
    if (encryptionPass === result.password) {
        // ctx.headers.
        ctx.body = { message: '登陆成功', result: { token } };
    } else {
        ctx.body = { message: '密码错误', result: false };
    }
}

module.exports = [
    { method: 'post', requestUrl: '/register', callback: registerRoute },
    { method: 'post', requestUrl: '/login', callback: loginRoute }
]